<?php
// Replace with your Facebook application's API Key and App Secret below
$appapikey = '--------Your-Key-Here-----------';
$appsecret = '-------Your-Secret-Here---------';

// Adapted heavily from Facebook client libraries...
$post = array('method' => 'facebook.auth.getSession',
              'api_key' => $appapikey,
              'v' => '1.0',
              'auth_token' => $_GET['auth_token'],
              'generate_session_secret' => 1/*TRUE*/);

if(isset($_GET['format']))
	$post['format'] = $_GET['format'];

$post['sig'] = generate_sig($post, $appsecret);

$post_params = array();
foreach ($post as $key => &$val) {
  $post_params[] = $key.'='.urlencode($val);
}
$post_string = implode('&', $post_params);

header('Content-Type: text/xml;charset=utf-8');
echo post('http://api.facebook.com/restserver.php', $post_string);

function post($url, $post_string) {
  if (function_exists('curl_init')) {
    $useragent = 'Facebook API PHP5 Client 1.1 (curl) ' . phpversion();
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $post_string);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_USERAGENT, $useragent);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
    $result = curl_exec($ch);
    curl_close($ch);
  }
  else {
    $user_agent = 'Facebook API PHP5 Client 1.1 (non-curl) ' . phpversion();
    $context =
      array('http' =>
              array('method' => 'POST',
                    'user_agent' => $user_agent,
                    'header' => "Content-Type: application/x-www-form-urlencoded\r\n" .
                                'Content-Length: ' . strlen($post_string),
                    'content' => $post_string));
    $context_id = stream_context_create($context);
    $sock = fopen($url, 'r', false, $context_id);

    $result = '';
    if ($sock) {
      while (!feof($sock)) {
        $result .= fgets($sock, 4096);
      }
      fclose($sock);
    }
  }
  return $result;
}

function generate_sig($params_array, $secret) {
  $str = '';

  ksort($params_array);
  // Note: make sure that the signature parameter is not already included in
  //       $params_array.
  foreach ($params_array as $k=>$v) {
    $str .= "$k=$v";
  }
  $str .= $secret;

  return md5($str);
}

